<?php

namespace App\Http\Controllers\Admin;

use App\Models\Role;
use App\Models\Permission;
use Illuminate\Http\Request;
use Validator;

use App\Http\Requests;
use App\Http\Controllers\BaseController;
use Illuminate\Support\Facades\DB;


class RoleController extends BaseController
{
    protected $fields = [
        'name' => '',
        'display_name' => '',
        'description' => '',
        'perms' => [],
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $roles = DB::table('roles')->paginate(15);
        return view('admin.role.index', compact('roles', $roles));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = [];
        $data['permissionAll'] = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $arr = Permission::all()->toArray();

        foreach ($arr as $v) {
            $data['permissionAll'][$v['cid']][] = $v;
        }
        //dd($data);
        return view('admin.role.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = $this->validateRole($request->all());
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        $role = new Role();
        foreach (array_keys($this->fields) as $field) {
            $role->$field = $request->get($field);
        }
        unset($role->perms);
        $role->save();
        if (is_array($request->get('permissions'))) {
            $role->givePermissionsTo($request->get('permissions'));
        }
        return redirect('admin/role')->with('success', '添加成功！');
    }

    //角色验证
    public function validateRole(array $data)
    {
        return Validator::make($data, [
            'name' => 'required',
            'display_name' => 'required',
        ], [
            'required' => ':attribute为必填项',
        ], [
            'name' => '角色名称',
            'display_name' => '角色别名'
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $role = Role::find((int)$id);
        if (!$role) return redirect('admin/role')->withErrors('找不到该角色！');
        $permissions = [];
        if ($role->perms) {
            foreach ($role->perms as $v) {
                $permissions[] = $v->id;
            }
        }
        $role->perms = $permissions;
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $role->$field);
        }
        $arr = Permission::all()->toArray();

        foreach ($arr as $v) {
            $data['permissionAll'][$v['cid']][] = $v;
        }
        $data['id'] = (int)$id;
        return view('admin.role.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = $this->validateRole($request->all());
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        $role = Role::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
            $role->$field = $request->get($field);
        }
        unset($role->perms);
        $role->save();
        $role->givePermissionsTo($request->get('permissions', []));
        return redirect('admin/role')->with('success', '编辑成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $role = Role::where('id', '=', (int)$id);
        if ($role) {
            $role->delete();
        } else {
            return redirect()->back()->withErrors('删除失败');
        }
        return redirect()->back()->withSuccess('删除成功');
    }
}
